package com.codeyang.controller;

import com.codeyang.domain.Category;
import com.codeyang.service.CategoryService;
import com.codeyang.vo.CategoryVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 描述: TO-删除标志-DO
 *
 * @author CodeYang_Site
 * @version 2021/5/25 14:55
 */
@Api(tags = "商品分类管理")
@RestController
@RequestMapping("prod/category")
public class CategoryController {


    @Autowired
    private CategoryService categoryService;

    @ApiOperation("全查询商品分类")
    @GetMapping("table")
    @PreAuthorize("hasAuthority('prod:category:page')")
    public ResponseEntity<List<Category>> table() {
        List<Category> categoryList = categoryService.list();
        return ResponseEntity.ok(categoryList);
    }


    @GetMapping("listCategory")
    @ApiOperation("全查询商品的所有父级分类")
    @PreAuthorize("hasAuthority('prod:category:page')")
    public ResponseEntity<List<Category>> listParentCategory() {
        List<Category> list = categoryService.loadParentCategory();
        return ResponseEntity.ok(list);
    }


    @ApiOperation("新增一个商品分类")
    @PostMapping
    @PreAuthorize("hasAuthority('prod:category:save')")
    public ResponseEntity<Void> addCategory(@RequestBody Category category) {
        //重写一下,因为 更新了DB 要更新缓存,要不然会引起脏读
        categoryService.save(category);
        return ResponseEntity.ok().build();
    }

    @PutMapping
    @ApiOperation("更新分类")
    @PreAuthorize("hasAuthority('prod:category:update')")
    public ResponseEntity<Void> updateCateGory(@RequestBody @Validated Category category) {
        categoryService.updateById(category);
        return ResponseEntity.ok().build();
    }

    @GetMapping("info/{id}")
    @ApiOperation("获得一个分类对象")
    @PreAuthorize("hasAuthority('prod:category:info')")
    public ResponseEntity<Category> info(@PathVariable Long id) {
        Category category = categoryService.getById(id);
        return ResponseEntity.ok().body(category);
    }

    @DeleteMapping("{id}")
    @ApiOperation("删除商品分类")
    @PreAuthorize("hasAuthority('prod:category:delete')")
    public ResponseEntity<Void> deleteCateGory(@PathVariable Long id) {
        categoryService.removeById(id);
        return ResponseEntity.ok().build();
    }
    //---- 前台调用的----

    @GetMapping("category/categoryInfo")
    @ApiOperation("加载所有的二级菜单")
    public ResponseEntity<List<CategoryVo>> loadAllSubCategorys() {
        List<CategoryVo> list = categoryService.loadAllSubCategorys();
        return ResponseEntity.ok(list);
    }
}
